package com.blue.seata.storage.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blue.seata.storage.entity.Storage;
import com.blue.seata.storage.mapper.StorageMapper;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author liulei
 * @version 1.0
 */
@Service
public class StorageService {

    private static final Logger logger = LoggerFactory.getLogger(StorageService.class);

    @Autowired
    private StorageMapper mapper;

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void minus(String code, int count) {
        String xid = RootContext.getXID();
        Storage storage = this.mapper.selectOne(new LambdaQueryWrapper<Storage>().eq(Storage::getCode, code));
        storage.setCount(storage.getCount() - count);
        this.mapper.updateById(storage);
        // 构建人为异常2
        if (count < 0 || storage.getCount() < 0) {
            throw new RuntimeException("库存中心人为异常..");
        }
        logger.info("扣减库存[{}],[{}],[{}]成功", code, count, xid);
    }
}
